/*
 *    Copyright (C) 2011-2012 Hai Bison
 *
 *    See the file LICENSE at the root directory of this project for copying
 *    permission.
 */

package group.pals.mailgate.ui;

import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;

/**
 *
 * @author Hai Bison
 */
public class JSpinnerMouseWheelHandler implements MouseWheelListener {

    private JSpinnerMouseWheelHandler() {
        //
    }

    public static JSpinnerMouseWheelHandler getInstance() {
        return JSpinnerMouseWheelHandlerHolder.INSTANCE;
    }

    private static class JSpinnerMouseWheelHandlerHolder {

        private static final JSpinnerMouseWheelHandler INSTANCE = new JSpinnerMouseWheelHandler();
    }

    /*----------------------------------------------------------------------------
     * IMPLEMENTATION
     */
    public void mouseWheelMoved(MouseWheelEvent e) {
        if (e.getComponent() instanceof JSpinner) {
            JSpinner spinner = (JSpinner) e.getComponent();
            if (spinner.getModel() instanceof SpinnerNumberModel) {
                SpinnerNumberModel model = (SpinnerNumberModel) spinner.getModel();
                Number number = (Number) model.getValue();
                int factor = e.getWheelRotation() < 0 ? 1 : -1;
                if (number instanceof Byte) {
                    number = number.byteValue() + factor * model.getStepSize().byteValue();
                } else if (number instanceof Short) {
                    number = number.shortValue() + factor * model.getStepSize().shortValue();
                } else if (number instanceof Integer) {
                    number = number.intValue() + factor * model.getStepSize().intValue();
                } else if (number instanceof Long) {
                    number = number.longValue() + factor * model.getStepSize().longValue();
                } else if (number instanceof Float) {
                    number = number.floatValue() + factor * model.getStepSize().floatValue();
                } else if (number instanceof Double) {
                    number = number.doubleValue() + factor * model.getStepSize().doubleValue();
                }

                if (model.getMinimum().compareTo(number) > 0) {
                    number = (Number) model.getMinimum();
                } else if (model.getMaximum().compareTo(number) < 0) {
                    number = (Number) model.getMaximum();
                }
                model.setValue(number);
            }
        }
    }
}
